import { useState, useEffect } from 'react';
import { 
  Drawer, 
  List, 
  Badge, 
  Button, 
  Tag, 
  Typography, 
  Space, 
  Empty, 
  Divider,
  Tooltip,
  Popconfirm
} from '@/utils/antd-imports';
import { 
  BellOutlined, 
  CloseOutlined, 
  CheckOutlined, 
  ExclamationCircleOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@/utils/icons';
import { NOTIFICATION_TYPES } from '../utils/notification';
import wsManager from '../utils/websocket';

const { Text, Title } = Typography;

export default function NotificationCenter() {
  const [visible, setVisible] = useState(false);
  const [notifications, setNotifications] = useState([]);
  const [unreadCount, setUnreadCount] = useState(0);

  // 初始化通知数据
  useEffect(() => {
    // 从本地存储加载通知历史
    const savedNotifications = localStorage.getItem('notifications');
    if (savedNotifications) {
      try {
        const parsed = JSON.parse(savedNotifications);
        setNotifications(parsed);
        setUnreadCount(parsed.filter(n => !n.read).length);
      } catch (error) {
        console.error('加载通知历史失败:', error);
      }
    }

    // 监听WebSocket消息
    const handleNotification = (payload) => {
      addNotification('notification', payload);
    };

    const handleAlert = (payload) => {
      addNotification('alert', payload);
    };

    const handleUrgent = (payload) => {
      addNotification('urgent', payload);
    };

    const handleApproval = (payload) => {
      addNotification('approval', payload);
    };

    const handleProject = (payload) => {
      addNotification('project', payload);
    };

    const handleSystem = (payload) => {
      addNotification('system', payload);
    };

    // 添加监听器
    wsManager.addListener('notification', handleNotification);
    wsManager.addListener('alert', handleAlert);
    wsManager.addListener('urgent', handleUrgent);
    wsManager.addListener('approval', handleApproval);
    wsManager.addListener('project', handleProject);
    wsManager.addListener('system', handleSystem);

    return () => {
      wsManager.removeListener('notification', handleNotification);
      wsManager.removeListener('alert', handleAlert);
      wsManager.removeListener('urgent', handleUrgent);
      wsManager.removeListener('approval', handleApproval);
      wsManager.removeListener('project', handleProject);
      wsManager.removeListener('system', handleSystem);
    };
  }, []);

  // 添加新通知
  const addNotification = (type, payload) => {
    const newNotification = {
      id: Date.now() + Math.random(),
      type,
      title: payload.title || payload.message || '新通知',
      description: payload.description || '',
      timestamp: new Date(),
      read: false,
      data: payload.data || {},
      actions: payload.actions || []
    };

    setNotifications(prev => {
      const updated = [newNotification, ...prev].slice(0, 100); // 最多保存100条
      localStorage.setItem('notifications', JSON.stringify(updated));
      return updated;
    });

    setUnreadCount(prev => prev + 1);
  };

  // 标记通知为已读
  const markAsRead = (id) => {
    setNotifications(prev => {
      const updated = prev.map(n => 
        n.id === id ? { ...n, read: true } : n
      );
      localStorage.setItem('notifications', JSON.stringify(updated));
      return updated;
    });
    setUnreadCount(prev => Math.max(0, prev - 1));
  };

  // 标记所有通知为已读
  const markAllAsRead = () => {
    setNotifications(prev => {
      const updated = prev.map(n => ({ ...n, read: true }));
      localStorage.setItem('notifications', JSON.stringify(updated));
      return updated;
    });
    setUnreadCount(0);
  };

  // 删除通知
  const deleteNotification = (id) => {
    setNotifications(prev => {
      const notification = prev.find(n => n.id === id);
      const updated = prev.filter(n => n.id !== id);
      localStorage.setItem('notifications', JSON.stringify(updated));
      
      // 如果删除的是未读通知，减少未读计数
      if (notification && !notification.read) {
        setUnreadCount(count => Math.max(0, count - 1));
      }
      
      return updated;
    });
  };

  // 清空所有通知
  const clearAllNotifications = () => {
    setNotifications([]);
    setUnreadCount(0);
    localStorage.removeItem('notifications');
  };

  // 获取通知图标
  const getNotificationIcon = (type) => {
    switch (type) {
      case 'alert':
        return <ExclamationCircleOutlined style={{ color: '#faad14' }} />;
      case 'urgent':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      case 'approval':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'project':
        return <InfoCircleOutlined style={{ color: '#1890ff' }} />;
      case 'system':
        return <WarningOutlined style={{ color: '#722ed1' }} />;
      default:
        return <BellOutlined style={{ color: '#8c8c8c' }} />;
    }
  };

  // 获取通知类型标签
  const getNotificationTag = (type) => {
    const tagMap = {
      'notification': { color: 'blue', text: '通知' },
      'alert': { color: 'orange', text: '预警' },
      'urgent': { color: 'red', text: '紧急' },
      'approval': { color: 'green', text: '审批' },
      'project': { color: 'cyan', text: '项目' },
      'system': { color: 'purple', text: '系统' }
    };
    
    const tag = tagMap[type] || { color: 'default', text: '其他' };
    return <Tag color={tag.color}>{tag.text}</Tag>;
  };

  // 格式化时间
  const formatTime = (timestamp) => {
    const now = new Date();
    const diff = now - timestamp;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return timestamp.toLocaleDateString();
  };

  return (
    <>
      <Tooltip title="通知中心">
        <Badge count={unreadCount} size="small">
          <Button
            type="text"
            icon={<BellOutlined />}
            onClick={() => setVisible(true)}
            style={{ fontSize: '16px' }}
          />
        </Badge>
      </Tooltip>

      <Drawer
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Space>
              <BellOutlined />
              <span>通知中心</span>
              {unreadCount > 0 && (
                <Badge count={unreadCount} size="small" />
              )}
            </Space>
            <Space>
              {unreadCount > 0 && (
                <Button size="small" onClick={markAllAsRead}>
                  全部已读
                </Button>
              )}
              {notifications.length > 0 && (
                <Popconfirm
                  title="确定要清空所有通知吗？"
                  onConfirm={clearAllNotifications}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button size="small" danger>
                    清空
                  </Button>
                </Popconfirm>
              )}
            </Space>
          </div>
        }
        placement="right"
        width={400}
        open={visible}
        onClose={() => setVisible(false)}
        closable={false}
      >
        {notifications.length === 0 ? (
          <Empty
            description="暂无通知"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          <List
            dataSource={notifications}
            renderItem={(item) => (
              <List.Item
                style={{
                  backgroundColor: item.read ? '#fafafa' : '#fff',
                  borderLeft: item.read ? 'none' : '3px solid #1890ff',
                  padding: '12px',
                  marginBottom: '8px',
                  borderRadius: '6px'
                }}
                actions={[
                  <Tooltip title="删除">
                    <Button
                      type="text"
                      size="small"
                      icon={<CloseOutlined />}
                      onClick={() => deleteNotification(item.id)}
                    />
                  </Tooltip>
                ]}
              >
                <List.Item.Meta
                  avatar={getNotificationIcon(item.type)}
                  title={
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Text strong={!item.read} style={{ fontSize: '14px' }}>
                        {item.title}
                      </Text>
                      <Space size="small">
                        {getNotificationTag(item.type)}
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          {formatTime(item.timestamp)}
                        </Text>
                      </Space>
                    </div>
                  }
                  description={
                    <div>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        {item.description}
                      </Text>
                      {item.actions && item.actions.length > 0 && (
                        <div style={{ marginTop: '8px' }}>
                          {item.actions.map((action, index) => (
                            <Button
                              key={index}
                              size="small"
                              type={action.type === 'primary' ? 'primary' : 'default'}
                              onClick={action.onClick}
                              style={{ marginRight: '8px', marginBottom: '4px' }}
                            >
                              {action.text}
                            </Button>
                          ))}
                        </div>
                      )}
                    </div>
                  }
                  onClick={() => !item.read && markAsRead(item.id)}
                  style={{ cursor: item.read ? 'default' : 'pointer' }}
                />
              </List.Item>
            )}
          />
        )}
      </Drawer>
    </>
  );
}
